package com.zmcn.fileTransfer.business.filetransfer.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;

import com.zmcn.fileTransfer.business.filetransfer.service.FileTransferService;
import com.zmcn.fileTransfer.business.filetransfer.vo.FileInfoVO;
import com.zmcn.fileTransfer.fw.action.BaseAction;
import com.zmcn.fileTransfer.fw.util.CodeUtil;
import com.zmcn.fileTransfer.fw.util.OutUtil;

@Action(value = "/sou")
public class FileSourceAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6182743231643591382L;

	private static final Log log = LogFactory.getLog(FileSourceAction.class);
	private FileTransferService service;

	@Autowired
	public void setService(FileTransferService service) {
		this.service = service;
	}

	/**
	 * 获取文件信息
	 * 
	 * @return
	 */
	public String getFileInfo() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			String token = ServletRequestUtils.getStringParameter(req, "token");
			if (service.checkToken(token)) {
				List<FileInfoVO> list = service.getFileInfo();
				map.put("info", list);
				map.put("code", CodeUtil.SUCCESS);
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 读取文件特定切片的字节流
	 * 
	 * @return
	 */
	public String readFile() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			String fileName = ServletRequestUtils.getStringParameter(req, "fileName");
			int batch = ServletRequestUtils.getIntParameter(req, "batch");
			int size = ServletRequestUtils.getIntParameter(req, "size");
			String token = ServletRequestUtils.getStringParameter(req, "token");
			if (service.checkToken(token)) {
				byte[] b = service.readFile(fileName, size, batch);
				OutUtil.outFile(b, fileName, getResponse());
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		return null;
	}

}
